<template>
  <div class="payment-container">
    <div v-if="!orderData || Object.keys(orderData).length === 0" class="no-order">
      <h2>未找到订单信息</h2>
      <p>请重新选择车次和乘客信息</p>
      <a-button type="primary" @click="goBack">返回订单页面</a-button>
    </div>

    <div v-else>
      <div class="payment-header">
        <h1>订单支付</h1>
        <div class="order-number">订单号: {{ orderData.orderNumber }}</div>
      </div>

      <a-divider class="custom-divider"></a-divider>

      <!-- 订单信息 -->
      <div class="order-info-section">
        <div class="section-header">
          <div class="header-icon">
            <ordered-list-outlined />
          </div>
          <h3>订单信息</h3>
        </div>

        <div class="train-card">
          <div class="train-header">
            <div class="train-badge">{{ orderData.dailyTrainTicket.trainCode }}次</div>
            <div class="train-info">
              <h2 class="train-title">{{ orderData.dailyTrainTicket.trainCode }}次列车</h2>
              <div class="train-date">{{ orderData.dailyTrainTicket.date }}</div>
            </div>
          </div>

          <div class="route-info">
            <div class="station start">
              <div class="station-name">{{ orderData.dailyTrainTicket.start }}站</div>
              <div class="station-time">{{ orderData.dailyTrainTicket.startTime }}</div>
            </div>

            <div class="route-line">
              <div class="line"></div>
              <div class="duration">约{{ calculateDuration(orderData.dailyTrainTicket) }}</div>
            </div>

            <div class="station end">
              <div class="station-name">{{ orderData.dailyTrainTicket.end }}站</div>
              <div class="station-time">{{ orderData.dailyTrainTicket.endTime }}</div>
            </div>
          </div>
        </div>

        <!-- 乘客和座位信息 -->
        <div class="passenger-seat-info">
          <div class="section-header">
            <div class="header-icon">
              <user-outlined />
            </div>
            <h3>乘客及座位信息</h3>
          </div>

          <div class="tickets-table">
            <div class="tickets-header">
              <div class="col-passenger">乘客</div>
              <div class="col-id">身份证</div>
              <div class="col-type">票种</div>
              <div class="col-seat">座位</div>
            </div>

            <div class="tickets-row" v-for="(ticket, index) in orderData.tickets" :key="ticket.passengerId">
              <div class="col-passenger">
                <user-outlined class="row-icon" />
                <span class="passenger-name">{{ ticket.passengerName }}</span>
              </div>
              <div class="col-id">{{ formatIdCard(ticket.passengerIdCard) }}</div>
              <div class="col-type">
                <span v-for="item in PASSENGER_TYPE_ARRAY" :key="item.code">
                  <span v-if="item.code === ticket.passengerType">{{ item.desc }}</span>
                </span>
              </div>
              <div class="col-seat">
                <span v-if="ticket.seat">{{ ticket.seat }}</span>
                <span v-else>系统分配</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <a-divider class="custom-divider"></a-divider>

      <!-- 支付信息 -->
      <div class="payment-section">
        <div class="section-header">
          <div class="header-icon">
            <dollar-outlined />
          </div>
          <h3>支付信息</h3>
        </div>

        <div class="payment-summary">
          <div class="summary-item">
            <span>车票总数：</span>
            <span class="summary-value">{{ orderData.tickets.length }}张</span>
          </div>
          <div class="summary-item">
            <span>总金额：</span>
            <span class="summary-value price">¥{{ orderData.totalPrice }}</span>
          </div>
        </div>

        <!-- 支付宝模拟支付 -->
        <div class="alipay-simulation">
          <div class="payment-method-header">
            <h4>选择支付方式</h4>
          </div>

          <div class="payment-methods">
            <div class="payment-method active">
              <img src="https://img.alicdn.com/tfs/TB1a2F6E4TpK1RjSZFKXXa2wXXa-200-200.png" alt="支付宝" class="method-logo">
              <span class="method-name">支付宝</span>
            </div>
          </div>

          <div class="alipay-qr-container">
            <div class="qr-code">
              <div class="qr-placeholder">
                <qrcode-vue :value="alipayUrl" :size="160" level="H" />
              </div>
              <p class="qr-hint">请使用支付宝扫一扫完成支付</p>
            </div>

            <div class="payment-actions">
              <a-button type="primary" size="large" @click="simulatePaymentSuccess" class="pay-btn">
                模拟支付成功
              </a-button>
              <a-button size="large" @click="simulatePaymentFailure" class="pay-btn">
                模拟支付失败
              </a-button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { notification } from 'ant-design-vue';
import {
  UserOutlined,
  OrderedListOutlined,
  DollarOutlined
} from '@ant-design/icons-vue';
import QrcodeVue from 'qrcode.vue';
import router from "@/router";

// 定义常量
const PASSENGER_TYPE_ARRAY = [
  { code: '1', desc: '成人' },
  { code: '2', desc: '儿童' },
  { code: '3', desc: '学生' },
  { code: '4', desc: '残疾军人' }
];

// 响应式数据
const orderData = ref({});
const alipayUrl = ref(`alipay://mock/payment/${Date.now()}`);

// 生命周期钩子
onMounted(() => {
  // 模拟从sessionStorage获取订单数据
  const mockOrderData = {
    dailyTrainTicket: {
      trainCode: 'G1234',
      date: '2023-12-20',
      start: '北京南',
      end: '上海虹桥',
      startTime: '08:00',
      endTime: '13:30'
    },
    tickets: [
      {
        passengerId: '1',
        passengerName: '张三',
        passengerIdCard: '110101199001011234',
        passengerType: '1',
        seat: '12A'
      },
      {
        passengerId: '2',
        passengerName: '李四',
        passengerIdCard: '110101199002022345',
        passengerType: '1',
        seat: '12B'
      }
    ],
    totalPrice: '523.50',
    orderNumber: `T${Date.now()}`
  };

  // 尝试从sessionStorage获取数据，如果不存在则使用模拟数据
  try {
    const storedData = sessionStorage.getItem('trainOrderData');
    if (storedData) {
      orderData.value = JSON.parse(storedData);
    } else {
      orderData.value = mockOrderData;
      console.log('使用模拟数据，实际应从sessionStorage获取');
    }
  } catch (e) {
    console.error('解析订单数据失败:', e);
    orderData.value = mockOrderData;
  }
});

// 计算行程时间
const calculateDuration = (dailyTrainTicket) => {
  if (!dailyTrainTicket.startTime || !dailyTrainTicket.endTime) return '-';

  const start = new Date(`2000-01-01T${dailyTrainTicket.startTime}`);
  const end = new Date(`2000-01-01T${dailyTrainTicket.endTime}`);
  if (end < start) end.setDate(end.getDate() + 1);

  const diff = Math.abs(end - start);
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

  return `${hours}小时${minutes}分`;
};

// 格式化身份证显示
const formatIdCard = (id) => {
  if (!id || id.length !== 18) return id;
  return `${id.substring(0, 6)}****${id.substring(14)}`;
};

// 模拟支付成功
const simulatePaymentSuccess = () => {
  notification.success({
    message: '支付成功',
    description: '您的车票已购买成功，请在"我的订单"中查看详情。',
    duration: 3,
  });

  // 3秒后跳转到订单成功页面
  setTimeout(() => {
    alert('支付成功！即将跳转到订单详情页面...');
    // 实际项目中这里应该是路由跳转
    router.push("/order-success")
  }, 3000);
};

// 模拟支付失败
const simulatePaymentFailure = () => {
  notification.error({
    message: '支付失败',
    description: '支付过程中出现问题，请重试或选择其他支付方式。',
    duration: 3,
  });
};

// 返回订单页面
const goBack = () => {
  alert('返回订单页面');
  // 实际项目中这里应该是路由跳转
  router.push("/order")
};
</script>

<style scoped>
.payment-container {
  max-width: 1000px;
  margin: 20px auto;
  padding: 20px;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
  color: #2d3748;
  background: #f9fafb;
  border-radius: 12px;
}

.payment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.payment-header h1 {
  margin: 0;
  color: #2d3748;
  font-size: 28px;
  font-weight: 700;
}

.order-number {
  color: #718096;
  font-size: 16px;
  font-weight: 500;
}

.custom-divider {
  margin: 30px 0;
  border-top: 1px solid #e2e8f0;
}

.order-info-section, .payment-section {
  background: white;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.05);
  padding: 25px;
  margin-bottom: 30px;
  border: 1px solid #e2e8f0;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 12px;
}

.header-icon {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #ebf8ff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #4299e1;
  flex-shrink: 0;
}

.section-header h3 {
  margin: 0;
  font-size: 18px;
  color: #2d3748;
  font-weight: 600;
}

.train-card {
  margin-bottom: 20px;
}

.train-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #edf2f7;
}

.train-badge {
  background: #3182ce;
  color: white;
  padding: 6px 14px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.train-info {
  flex: 1;
  padding: 0 20px;
}

.train-title {
  font-size: 24px;
  color: #2d3748;
  margin: 0 0 5px 0;
  font-weight: 700;
}

.train-date {
  color: #718096;
  font-size: 15px;
  font-weight: 500;
}

.route-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 30px 0;
  position: relative;
}

.station {
  flex: 1;
  text-align: center;
  padding: 15px;
  border-radius: 10px;
  background: #f7fafc;
  position: relative;
  z-index: 2;
}

.station.start {
  border: 1px solid #c3dafe;
}

.station.end {
  border: 1px solid #fed7d7;
}

.station-name {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 5px;
  color: #2d3748;
}

.station-time {
  color: #4a5568;
  font-size: 16px;
  font-weight: 500;
}

.route-line {
  flex: 1;
  position: relative;
  text-align: center;
  z-index: 1;
}

.line {
  height: 2px;
  background: linear-gradient(to right, #4299e1, #f56565);
  margin: 0 10px;
  position: relative;
}

.line::before, .line::after {
  content: '';
  position: absolute;
  top: -3px;
  width: 8px;
  height: 8px;
  background: #4299e1;
  border-radius: 50%;
}

.line::after {
  background: #f56565;
  right: 0;
  left: auto;
}

.duration {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  padding: 5px 15px;
  color: #4a5568;
  font-size: 14px;
  font-weight: 500;
  border-radius: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.tickets-table {
  border: 1px solid #edf2f7;
  border-radius: 10px;
  overflow: hidden;
  margin-top: 20px;
}

.tickets-header {
  display: flex;
  background: #f7fafc;
  color: #4a5568;
  font-weight: 600;
  padding: 15px 20px;
  border-bottom: 1px solid #e2e8f0;
}

.tickets-row {
  display: flex;
  padding: 15px 20px;
  border-bottom: 1px solid #edf2f7;
  transition: background 0.2s;
  align-items: center;
}

.tickets-row:last-child {
  border-bottom: none;
}

.tickets-row:hover {
  background: #f8fafc;
}

.col-passenger, .col-id, .col-type, .col-seat {
  padding: 0 10px;
}

.col-passenger {
  flex: 2;
  display: flex;
  align-items: center;
}

.row-icon {
  margin-right: 8px;
  color: #4299e1;
}

.passenger-name {
  font-weight: 500;
}

.col-id {
  flex: 6;
  color: #4a5568;
  font-size: 14px;
}

.col-type, .col-seat {
  flex: 4;
}

.payment-summary {
  display: flex;
  justify-content: flex-end;
  gap: 20px;
  margin: 20px 0;
  padding-bottom: 20px;
  border-bottom: 1px dashed #e2e8f0;
}

.summary-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  color: #4a5568;
}

.summary-value {
  font-weight: 600;
  color: #2d3748;
}

.price {
  font-size: 20px;
  color: #dd6b20;
}

.alipay-simulation {
  margin-top: 25px;
}

.payment-method-header {
  margin-bottom: 20px;
}

.payment-method-header h4 {
  margin: 0;
  color: #2d3748;
  font-size: 18px;
  font-weight: 600;
}

.payment-methods {
  display: flex;
  gap: 15px;
  margin-bottom: 25px;
}

.payment-method {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 12px 20px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.payment-method.active {
  border-color: #1890ff;
  background-color: #e6f7ff;
}

.method-logo {
  width: 30px;
  height: 30px;
  object-fit: contain;
}

.method-name {
  font-weight: 500;
  color: #2d3748;
}

.alipay-qr-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
  padding: 30px;
  background: #f7fafc;
  border-radius: 12px;
}

.qr-code {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.qr-placeholder {
  width: 180px;
  height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: white;
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.qr-hint {
  margin: 0;
  color: #718096;
  font-size: 14px;
  text-align: center;
}

.payment-actions {
  display: flex;
  gap: 15px;
  margin-top: 15px;
}

.pay-btn {
  min-width: 140px;
  height: 44px;
  font-weight: 600;
}

.no-order {
  text-align: center;
  padding: 50px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.05);
}

@media (max-width: 768px) {
  .payment-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  .payment-summary {
    flex-direction: column;
    gap: 10px;
    align-items: flex-end;
  }
  .alipay-qr-container {
    padding: 20px;
  }
  .payment-actions {
    flex-direction: column;
    width: 100%;
  }
  .pay-btn {
    width: 100%;
  }
  .tickets-header, .tickets-row {
    flex-direction: column;
    gap: 15px;
  }
  .col-passenger, .col-id, .col-type, .col-seat {
    padding: 8px 0;
    width: 100%;
  }
}
</style>